﻿using System;
using System.Workflow.Activities;
using System.Xml.Serialization;
using System.Xml;
using Microsoft.SharePoint;
using System.Net;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.WorkflowActions;
using System.Text;
using UpdateContentType;

namespace UpdateContentType
{
    public sealed partial class PortalWorkflow : SequentialWorkflowActivity
    {
        #region Members
        public Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties workflowProperties = new Microsoft.SharePoint.Workflow.SPWorkflowActivationProperties();
        public String historyDescription = default(System.String);

        private string _url = default(string);
        private string _urlTFSWS = default(string);
        private string _errorEmailTo = default(string);
        private int _contentTypes = 0;
        #endregion

        public PortalWorkflow()
        {
            InitializeComponent();
        }

        #region Events
        private void DefineAssociation_ExecuteCode(object sender, EventArgs e)
        {
            UpdateContentTypeAssociationData myAssociationData = null;   // Represents the Association Form Data pased in
            XmlSerializer serializer;
            XmlTextReader reader;

            // Deserialize the Custom Workflow Form Data from a String, 
            // back into the the appropriate Class Type so that we can use 
            // the values in our workflow.  
            serializer = new XmlSerializer(typeof(UpdateContentTypeAssociationData));
            reader = new XmlTextReader(new System.IO.StringReader(workflowProperties.AssociationData));
            myAssociationData = (UpdateContentTypeAssociationData)serializer.Deserialize(reader);

            // Store the user selected values
            this._urlTFSWS = myAssociationData.urlTFSWS;
            this._errorEmailTo = myAssociationData.errorEmailTo;
        }

        private void UpdateTemplatePortal_ExecuteCode(object sender, EventArgs e)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                Common c = new Common(workflowProperties.Site.Url, workflowProperties.Item.File.Name, workflowProperties.Item.File.OpenBinary());
                _contentTypes = c.UpdateTemplate();
            });

            _url = workflowProperties.Site.Url;
        }

        private void UpdateTemplateTFS_ExecuteCode(object sender, EventArgs e)
        {
            _contentTypes = 0;

            UpdateService.TFSWebService ws = new UpdateService.TFSWebService();
            ws.Url = _urlTFSWS;
            ws.Credentials = CredentialCache.DefaultCredentials;

            Uri uri = new Uri(_urlTFSWS);
            string portalUrl = string.Format("{0}://{1}", uri.Scheme, uri.Host);

            _contentTypes = ws.UpdateTemplate(portalUrl, workflowProperties.Item.File.Name, workflowProperties.Item.File.OpenBinary());
            _url = portalUrl + "/";
        }

        private void logTemplateUpdated_MethodInvoking(object sender, EventArgs e)
        {
            historyDescription = string.Format("{0} tipo(s) de conteúdo atualizado(s) em {1}.", _contentTypes, _url);
        }

        private void sendEmailError_MethodInvoking(object sender, EventArgs e)
        {
            StringBuilder body = new StringBuilder();
            body.Append("<b>******** SOURCE ********</b><br/>");
            body.Append(faultHandlerSystemException.Fault.Source + "<br/><br/>");
            body.Append("<b>******** MESSAGE ********</b><br/>");
            body.Append(faultHandlerSystemException.Fault.Message + "<br/><br/>");
            body.Append("<b>******** STACK TRACE ********</b><br/>");
            body.Append(faultHandlerSystemException.Fault.StackTrace);

            ((SendEmail)sender).Body = body.ToString();
            ((SendEmail)sender).Subject = "Ocorreu um erro ao executar o workflow de atualização de tipos de conteúdo";
            ((SendEmail)sender).To = _errorEmailTo;
        }
        #endregion
    }

    [Serializable]
    public class UpdateContentTypeAssociationData
    {
        public string urlTFSWS;
        public string errorEmailTo;
    }
}
